package cn.gson.financial.kernel.utils;

import lombok.extern.slf4j.Slf4j;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.ParseException;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.CoreConnectionPNames;
import org.apache.http.protocol.HTTP;
import org.apache.http.util.EntityUtils;

import javax.servlet.http.HttpServletRequest;
import java.io.*;
import java.net.InetAddress;
import java.net.URL;
import java.net.URLConnection;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

@Slf4j
public class HttpClientUtils {

    /**
     * get请求
     * @param url
     * @return
     */
    public static String httpGet(String url){
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
        HttpGet get = new HttpGet(url);
        // 设置请求头
        get.setHeader("Content-type", "application/json; charset=utf-8");
        try {
            HttpResponse response = httpClient.execute(get);
            result = reponse2String(response);
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * post请求
     * @param url
     * @param params
     * @return
     */
    public static String httpPost(String url, Map<String,Object> params){
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
        HttpPost post = null;
        post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        // 参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for(String key:keySet){
            list.add(new BasicNameValuePair(key, params.get(key).toString()));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(post);
            result = reponse2String(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * post请求
     * @param url
     * @param params
     * @return
     */
    public static String httpPostJson(String url,String params){
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
        HttpPost post = null;
        post = new HttpPost(url);
        try {
            StringEntity s = new StringEntity(params);
            s.setContentEncoding("utf-8");
            s.setContentType("application/json; charset=utf-8");
            post.setEntity(s);
            HttpResponse response = httpClient.execute(post);
            result = reponse2String(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * get请求(爬虫)
     * @param url
     * @return
     * @throws Exception
     * @throws
     */
    public static String httpReptileGet(String url,String cookie,String tk) throws Exception{
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
        HttpGet get = new HttpGet(url);
        // 设置请求头
        //get.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        get.setHeader("Cookie",cookie);
        get.setHeader("tk",tk);
        HttpResponse response = httpClient.execute(get);
        result = reponse2String(response);
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * post请求(爬虫)
     * @param url
     * @param params
     * @return
     */
    public static String httpReptilePost(String url,Map<String,String> params,String cookie,String tk){
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
        HttpPost post = null;
        post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        post.setHeader("Cookie",cookie);
        post.setHeader("tk",tk);
        // 参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for(String key:keySet){
            list.add(new BasicNameValuePair(key, params.get(key)));
        }
        try {
            post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
            HttpResponse response = httpClient.execute(post);
            result = reponse2String(response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * post请求,返回状态码
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String httpPost(String url,Map<String,String> params,String cookie,String tk) throws Exception{
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
        HttpPost post = null;
        post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        post.setHeader("Cookie",cookie);
        post.setHeader("tk",tk);
        // 参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for(String key:keySet){
            list.add(new BasicNameValuePair(key, params.get(key)));
        }
        post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        HttpResponse response = httpClient.execute(post);
        result = String.valueOf(response.getStatusLine().getStatusCode());
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * post请求,返回状态码(vivo请求，需要格式化参数，单独写)
     * @param url
     * @param params
     * @return
     * @throws Exception
     */
    public static String httpVivoPost(String url,Map<String,String> params,String cookie) throws Exception{
        String result = null;
        HttpClient httpClient = new DefaultHttpClient();
        httpClient.getParams().setParameter(CoreConnectionPNames.CONNECTION_TIMEOUT, 60000); // 连接超时时间
        httpClient.getParams().setParameter(CoreConnectionPNames.SO_TIMEOUT, 90000);  // 数据传输时间
        HttpPost post = null;
        post = new HttpPost(url);
        // 设置请求头
        post.setHeader("Content-type", "application/x-www-form-urlencoded; charset=utf-8");
        post.setHeader("Cookie",cookie);
        // 参数
        List<NameValuePair> list = new ArrayList<NameValuePair>();
        Set<String> keySet = params.keySet();
        for(String key:keySet){
            if(key.indexOf("ideaUpdateRequest.wordList")!=-1){
                list.add(new BasicNameValuePair("ideaUpdateRequest.wordList", params.get(key)));
            }else{
                list.add(new BasicNameValuePair(key, params.get(key)));
            }
        }
        post.setEntity(new UrlEncodedFormEntity(list, HTTP.UTF_8));
        HttpResponse response = httpClient.execute(post);
        result = String.valueOf(response.getStatusLine().getStatusCode());
        // 关闭
        httpClient.getConnectionManager().shutdown();
        return result;
    }

    /**
     * 获取客户端ip(外网)
     * @param request
     * @return
     */
    public static String getIp(HttpServletRequest request){
        String ip = request.getHeader("X-Forwarded-For");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("Proxy-Client-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("WL-Proxy-Client-IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_CLIENT_IP");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getHeader("HTTP_X_FORWARDED_FOR");
        if (ip == null || ip.length() == 0 || "unknown".equalsIgnoreCase(ip))
            ip = request.getRemoteAddr();
        if ("127.0.0.1".equals(ip) || "0:0:0:0:0:0:0:1".equals(ip))
            try {
                ip = InetAddress.getLocalHost().getHostAddress();
            }
            catch (UnknownHostException unknownhostexception) {
            }
        return ip;
    }

    /**
     * 转化返回参数
     * @param response
     * @return
     */
    public static String reponse2String(HttpResponse response){
        HttpEntity entity = response.getEntity();
        String body = null;
        try {
            body = EntityUtils.toString(entity);
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return body;
    }


    public static String sendPost(String url, String param) {
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            //设置通用的请求属性
            conn.setRequestProperty("user-agent","Mozilla/5.0 (Windows NT 6.1; WOW64; rv:21.0) Gecko/20100101 Firefox/21.0)");
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            OutputStreamWriter outWriter = new OutputStreamWriter(conn.getOutputStream(), "utf-8");
            out = new PrintWriter(outWriter);
            // 发送请求参数
            out.print(param);
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                in = new BufferedReader(new InputStreamReader(conn.getInputStream()));result += line;
            }
        } catch (Exception e) {
            log.info("发送 POST 请求出现异常！"+e);
            e.printStackTrace();
        }
        //使用finally块来关闭输出流、输入流
        finally{
            try{
                if(out!=null){
                    out.close();
                }
                if(in!=null){
                    in.close();
                }
            }
            catch(IOException ex){
                ex.printStackTrace();
            }
        }
        return result;
    }

}
